'use strict';

const Controller = require('egg').Controller;
const eurekaUtils = require('../utils/eurekaUtils');

const rule = {
  name: [
    { required: true },
    { type: 'number', message: 'id 必须为数字' },
  ],
  password: [
    { required: true },
    { type: 'string', message: 'password 必须为字符串' },
  ],
};

class HomeController extends Controller {
  async index() {
    const { ctx } = this;

    ctx.body = 'hi, egg！！！';

  }

  /**
   * 校验
   */
  async fetch() {
    const { ctx } = this;
    const { query } = this.ctx.request;
    // console.log(ctx.request);
    ctx.logger.info(query);
    const validateResult = await ctx.validate(rule, query);
    if (!validateResult) return;

    this.ctx.body = this.app;
  }

  /**
   * 通过 eureka 消费 Spring Cloud 生产者服务
   */
  async eureka() {
    const instances = this.app.eureka.getInstancesByAppId('provider');
    this.ctx.logger.warn(instances);
    // 负载均衡调用生产者 @todo
    const url = eurekaUtils.getServerUrl(instances[0]);
    const resutlt = await this.app.curl(`${url}/user/${this.ctx.params.id}`, { dataType: 'json' });
    this.ctx.body = resutlt.data;
  }

}

module.exports = HomeController;
